package com.opesoft.pf.rules;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import com.opesoft.fw.validate.Rule;
import com.opesoft.pf.jpa.SessionManager;

public class UniqueRule implements Rule
{

	@SuppressWarnings("unchecked")
	@Override
	public String check(Object v,Map<String, Object> ps) throws Exception
	{
		String sql=ps.get("sql")+"";

		EntityManager em=SessionManager.open();
		try
		{
			Query q=em.createQuery(sql);
			q.setFirstResult(0);
			q.setMaxResults(1);
			List list=q.getResultList();

			SessionManager.rollback();

			if(list.size()>0)
			{
				if(ps.get("msg")!=null) return ps.get("msg")+"";
				else return "${name}'s value is not unique!";
			}
		}
		catch(Exception e)
		{
			throw e;
		}
		finally
		{
			SessionManager.close();
		}

		return null;
	}

}
